/*
 * @Author: shiguo
 * @Date: 2022-04-24 14:27:02
 * @LastEditors: shiguo
 * @LastEditTime: 2022-09-09 10:55:48
 * @FilePath: /@aks-dev/easyui/lib/Hud/Loading/Loading.tsx
 */
import React, { useImperativeHandle, useState } from 'react';
import { View, ActivityIndicator, StyleSheet, Text, Dimensions, TouchableOpacity, BackHandler } from 'react-native';

import { LoadingOptions } from '.'





export const Loading = React.forwardRef<LoadingOptions.RefAttributes, {}>((_, ref) => {
    const [show, setShow] = useState(false);
    const [tipText, setTipText] = useState('加载中');


    React.useEffect(() => {
        const onBackPress = () => show;
        BackHandler.addEventListener('hardwareBackPress', onBackPress);
        return () => BackHandler.removeEventListener('hardwareBackPress', onBackPress);
    }, [show])


    useImperativeHandle<unknown, LoadingOptions.RefAttributes>(ref, () => ({
        showLoading: (content?: string) => {
            setShow(true);
            setTipText(content || '加载中')
        },
        hideLoading: () => {
            setShow(false);
        }
    }), [show])

    if (!show)
        return null;

    return (
        <TouchableOpacity disabled style={styles.container}>
            <View style={styles.warpper}>
                <ActivityIndicator color="white" size='large' />
                <Text numberOfLines={5} style={styles.title}>{tipText}
                </Text>
            </View>
        </TouchableOpacity>
    )
})

export const loadingRef = React.createRef<LoadingOptions.RefAttributes>();
export const showLoading = (content?: string) => loadingRef.current?.showLoading(content)
export const hideLoading = () => loadingRef.current?.hideLoading()



const SCREEN_WIDTH = Dimensions.get('window').width;
const styles = StyleSheet.create({
    container: {
        ...StyleSheet.absoluteFillObject,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        // backgroundColor:'red'
    },

    warpper: {
        backgroundColor: '#00000088',
        padding: 40,
        paddingVertical: 20,
        borderRadius: 10,
        justifyContent: 'center',
        alignItems: 'center',
        minWidth: 90
    },
    title: {
        marginTop: 5,
        fontSize: 13,
        lineHeight: 16,
        color: 'white',
        maxWidth: SCREEN_WIDTH * 0.5,

    }

})
